package com.example.demo.Control;
import com.example.demo.Common.AjaxResult;
import com.example.demo.Common.PasswordTools;
import com.example.demo.Common.Session;
import com.example.demo.Entity.Userinfo;
import com.example.demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/chatRoom")
public class Usercontrol {
    @Autowired
    public UserService userService;
    @RequestMapping("/resign")
    public AjaxResult insert(Userinfo userinfo){
        if(userinfo==null|| !StringUtils.hasLength(userinfo.getUsername()) ||!StringUtils.hasLength(userinfo.getPassword())){
            return AjaxResult.fail(-1,"参数有误");
        }
        Userinfo userinfo1= userService.selectByName(userinfo.getUsername());
        if(userinfo1!=null){
            return AjaxResult.fail(-1,"用户名重复");
        }
        String password= PasswordTools.encrypt(userinfo.getPassword());
        userinfo.setPassword(password);
        int result=userService.insert(userinfo);
        return AjaxResult.success(result);
    }
    @RequestMapping("/login")
    public AjaxResult selectByName(String username, String password, HttpServletRequest req){
        if(username==null|| !StringUtils.hasLength(username) ||password==null||!StringUtils.hasLength(password)){
            return AjaxResult.fail(-1,"参数有误");
        }
        Userinfo userinfo= userService.selectByName(username);
        if(userinfo==null||userinfo.getUserid()<=0){
            return AjaxResult.fail(-1,"用户名或密码错误");
        }
        if(!PasswordTools.decrypt(password,userinfo.getPassword())){
            return AjaxResult.fail(-1,"用户名或密码错误");
        }
        //保存到会话中
        HttpSession session= req.getSession();
        session.setAttribute(Session.SEESSINO_KEY,userinfo);
        session.setAttribute("userinfo", userinfo);
        return AjaxResult.success(userinfo);
    }
    @RequestMapping("/getUser")
    public AjaxResult getUserInfo(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            return AjaxResult.fail(-1,"请重新登录");
        }
        Userinfo userinfo=(Userinfo) session.getAttribute(Session.SEESSINO_KEY);
       return AjaxResult.success(userinfo);
    }
}
